package com.example.boot3.controller;

import com.example.boot3.service.JwtTokenService;
import com.example.boot3.service.UserService;
import com.example.boot3.util.JsonData;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;


import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import java.util.Map;
import java.util.UUID;

@CrossOrigin(origins =  "*")
@RestController

public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private  JwtTokenService jwtTokenService;
    @Autowired
    private ResourceLoader resourceLoader;

    @PostMapping("edit_pwd")
    public JsonData changePwd(HttpServletRequest request, @RequestBody Map<String,String> newPwdRequest){
        String token=request.getHeader("Authorization");
        String user_id = jwtTokenService.getUserIdFromToken(token);
        System.out.println("修改密码"+user_id);
        String md5Password = DigestUtils.md5DigestAsHex(newPwdRequest.get("new_password").getBytes());
        return JsonData.buildSuccess(userService.changePwd(md5Password,user_id));
    }



    @PostMapping("avatar/upload")
    public JsonData upLoadAvatar(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {

        //如果没有创建目录
        String directoryPath = "uploads/";
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            directory.mkdirs(); // 创建目录及其父目录
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件存储路径
        String filePath = "uploads/" + fileName;

        // 将文件保存到服务器上的指定目录
        byte[] bytes = file.getBytes();
        Path path = Paths.get(filePath);
        Files.write(path, bytes);

        // **生成文件的在线地址并返回,不必使用代理
        String fileUrl = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/uploads/")
                .path(fileName)
                .toUriString();
        System.out.println(fileUrl);
        // 持久化存储"/avatar/"+fileNam
        String token=request.getHeader("Authorization");
        if(token!=null){
            System.out.println(token);
            String user_id = jwtTokenService.getUserIdFromToken(token);
            userService.upLoadAvatar(fileUrl,user_id);
        }

        return JsonData.buildSuccess(fileUrl);
    }

}

